package com.zhengjiang.api.demo.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Map;

public class RestTemplateUtil {

    public static <T> T postForm(String url, MultiValueMap<String, String> param, Map<String,String> headParams, Class<T> respType) {
        return getRestInstance().postForEntity(url, getHttpEntity(param,headParams ,false), respType).getBody();
    }

    private static <P> HttpEntity<P> getHttpEntity(P param, Map<String,String> headParams,boolean isJson) {
        HttpHeaders headers = new HttpHeaders();
        if (isJson) {
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        } else {
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        }
        if(headParams!=null){
            headParams.forEach((k,v)->{
               headers.set(k,v);
            });
        }
        return new HttpEntity<>(param, headers);
    }

    /*-----------------生产单例对象，方便自定义如何构造对象------------------*/
    private static RestTemplate restInit() {
        //设置连接超时和读取超时时间
        SimpleClientHttpRequestFactory factory=new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(5000);
        factory.setReadTimeout(5000);
        RestTemplate restTemplate = new RestTemplate(factory);
        FormHttpMessageConverter fastConverter = new FormHttpMessageConverter();
        MappingJackson2HttpMessageConverter mapConverter = new MappingJackson2HttpMessageConverter();
        restTemplate.getMessageConverters().add(fastConverter);
        restTemplate.getMessageConverters().add(mapConverter);
        return restTemplate;
    }

    private static RestTemplate getRestInstance() {
        return RestSingle.INSTANCE;
    }

    private static class RestSingle {
        private static final RestTemplate INSTANCE = restInit();
    }
}
